﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using Marbles.Core.Helpers;
using Marbles.Core.Web.MVC.Views;

namespace Marbles.Core.Web.State
{
    public class CompressedStatePersistanceManager : IStatePersistanceManager
    {

        private CompressionMethod _provider = CompressionMethod.Zip;

        public CompressedStatePersistanceManager(CompressionMethod CompressionMethod)
        {
            this._provider = CompressionMethod;
        }

        public string SavePageStateToPersistenceMedium(object state, ViewBase Page)
        {
            StringWriter sw = new StringWriter();
            LosFormatter ser = new LosFormatter();
            ser.Serialize(sw, state);
            sw.Flush();
            HtmlInputHidden field = new HtmlInputHidden();
            field.ID = "__VS";
            field.Value = Compression.Compress(sw.ToString(), this._provider);
            Page.Form.Controls.Add(field);
            return Page.ViewStateKey;
        }

        public object LoadPageStateFromPersistenceMedium(ViewBase Page)
        {
            LosFormatter ser = new LosFormatter();
            string value = Page.Request["__VS"];
            if (value != string.Empty)
            {
                return ser.Deserialize(Compression.Decompress(value, this._provider));
            }

            return null;
        }
    }

}

